﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using S.Archives.Domain.S.ArchivesModel;
using S.Common.Enums.Archives;
using S.EarTag.Domain.ApiResult;
using S.EarTag.Domain.Dto;
using S.EarTag.Infrastructure.Repository.Interface.IRepository;
using S.EarTag.Read.API.Application.MediatorCommand.ProductionGradingCommand;
using SqlSugar;
using static System.Net.WebRequestMethods;

namespace S.EarTag.Read.API.Application.MediatorCommandHandler.ProductionGradingCommandHandler
{
    public class ProductionGradingSeachCommandHandler : IRequestHandler<ProductionGradingSeachCommand, ApiResult<List<ProductionGradingDto>>>
    {
        private readonly IProductionGradingRepository _productionGradingRepository;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IConfiguration _configuration;

        public ProductionGradingSeachCommandHandler(IProductionGradingRepository productionGradingRepository,IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            _productionGradingRepository = productionGradingRepository;
            _httpContextAccessor = httpContextAccessor;
            _configuration = configuration;
        }
        /// <summary>
        /// 条件查询显示生产定级方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<ProductionGradingDto>>> Handle(ProductionGradingSeachCommand request, CancellationToken cancellationToken)
        {
            var productionGradings = await _productionGradingRepository.GetAllAsync();

            var i = _configuration["eartagurl"];

            string authHeader = _httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer "))
            {
                authHeader = authHeader.Substring("Bearer ".Length).Trim();
            }

            // 构造 HTTP 请求
            HttpClient httpClient = new HttpClient();
            HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, $"{i}/ach/api/SheepFileModel/GetSheepFilesAll");
            HttpResponseMessage httpResponse = await httpClient.SendAsync(httpRequest);

            //if (httpResponse.IsSuccessStatusCode)
            //{
                // 读取响应内容
                string responseContent = await httpResponse.Content.ReadAsStringAsync();

                // 反序列化响应内容为 SheepFileModel 的列表
                List<SheepFileModel> sheepFiles = JsonConvert.DeserializeObject<List<SheepFileModel>>(responseContent);
                
                // 使用 LINQ 进行联接查询
                var query = from grading in productionGradings
                            join sheepFile in sheepFiles on grading.RankEarTag equals sheepFile.EarTag
                            where ((request.SheepType==0 || sheepFile.FileType==request.SheepType)
                             && (string.IsNullOrEmpty(request.RankEarTag) || grading.RankEarTag.Contains(request.RankEarTag) && (request.Current==0 || grading.Currents==request.Current)))
                            select new ProductionGradingDto
                            {
                                // 根据需要选择要映射的属性
                                ProductionGradingId= grading.ProductionGradingId,
                                RankEarTag= grading.RankEarTag,
                                SheepType= (SheepType)sheepFile.FileType,
                                Prime=grading.Prime,
                                Current=grading.Currents,
                                CreateBy=grading.CreateBy,
                                CreateDate=grading.CreateDate,
                                // 其他需要的属性
                            };

                // 执行查询并获取结果
                var mergedList = query.ToList();

                // 构造 ApiResult 对象
                ApiResult<List<ProductionGradingDto>> apiResult = new ApiResult<List<ProductionGradingDto>>();
                apiResult.Data = mergedList;
                apiResult.totalCount = mergedList.Count;
            apiResult.pageCount = (int)Math.Ceiling((apiResult.totalCount * 1.0) / request.pageSize);

                // 分页处理
                apiResult.Data = mergedList.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                return apiResult;
            //}
            //else
            //{
            //    // 处理请求失败情况...
            //}
        }
    }
}
